import { ReactElement } from "react";
import { useLocation, Navigate } from "react-router-dom";
const whiteList: string[] = [
  "/login",
  "/home",
  "/list",
  "/detail",
  "/detail/editor",
  "/search",
  "/info",
  "/letter",
  "/practice",
  "/publish",
  "/video",
];

const Guard = ({ children }: { children: ReactElement }) => {
  const { pathname } = useLocation();
  console.log(pathname);

  const nextPath = onRouterBefore(pathname);
  console.log(nextPath);

  if (nextPath && nextPath !== pathname) {
    children = <Navigate to="/login" replace={true} />;
  }
  console.log(children);

  return children;
};

const onRouterBefore = (pathname: string): string => {
  const token = sessionStorage.getItem("token");
  if (whiteList.includes(pathname) && token) {
    //  加上你的判断条件 白名单、是否登陆、是否有权限进入
    return pathname;
  }
  // if return router路径是否有权限进入的认证，可结合系统授权返回菜单
  return "/login";
};

export default Guard;
